<template>
	<view>
		<view class="w-full state-area dflex navbar-area bg-main">
			<view class="nav-item dflex-c pos-r fs h-full" :class="{ active: reqdata.payType == item.payType }"
				v-for="(item, index) in navList" :key="index" @click="tabClick(index,item.payType)">
				{{ item.state }}
			</view>
		</view>
		<view :class="[empty ? '' : 'padding-lr-sm']">
			<!-- 空白页 -->
			<use-empty v-if="empty" e-style="round" e-type="cart" :btn-tip="false" tip="暂无记录"></use-empty>

			<view v-else class="padding bg-main border-radius margin-top-sm pos-r"  v-for="(item, idx) in datas" @click="toGoods(item)" :key="idx">
				<view class="dflex-b">
					<view>
						<view class="fwb">{{ item.productTitle  }}✖️{{item.totalNum}}</view>
						<view  class="ft-dark fs-xxs">{{item.contacts}} {{ item.mobile }} 备注:{{item.remark}}</view>
						<view  class="ft-dark fs-xxs">{{ item.shippingAddress }}</view>
						<view  class="ft-dark fs-xxs" v-if="item.deliveryId">{{ item.deliveryName }}:{{ item.deliveryId }}</view>
					</view>
					<view class="dflex-c dflex-flow-c">
						<view class="">
							<text class="fwb">{{item.payPrice}}</text>
						</view>
						<view class="">
							<view v-if="item.status==0" class="bg-base border-radius" @click.stop="confirmOrder(item)" style="padding: 6rpx 20rpx;">
								确认收货
							</view>
							<view v-else-if="item.status==-2" class="bg-base border-radius" @click.stop="payOrder(item)" style="padding: 6rpx 20rpx;">
								去支付
							</view>
							<view v-else>
								{{item.status==-1?"未发货":"已签收"}}
							</view>
						</view>
					</view>
				</view>
				<view class="bg-base fs-xxs pos-a pos-top pos-right" style="border-bottom-left-radius: 20rpx; padding: 2rpx 10rpx;">
					{{ $api.format(item.payTime, 'yyyy-MM-dd hh:mm') }}
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import { mapState } from 'vuex';
	import {goods_redeem_order,redeem_confirm,get_order_by_id} from "../../../js_sdk/apis/order.js"
	export default {
		computed: {
			userInfo(){
				return this.$store.state.user.userInfo
			},
			isLogin(){
				return this.$store.getters['user/hasLogin']
			}
		},
		data() {
			return {
				empty: false,
				state: '',
				// 加载更多状态
				loadmoreType: 'more',
				navList: [{
					payType:0,
					state: '平台余额订单'
				},
				{
					payType:1,
					state: '平台积分订单'
				},{
					payType:3,
					state: '专享金订单'
				}],
				// 请求数据
				reqdata: {
					current: 1,
					size: 20,
					payType:0,
					sidx: 'sort',
					sord: 'asc'
				},
				datas: []
			};
		},
		//下拉刷新
		onPullDownRefresh() {
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom() {
			this.loadData();
		},
		onLoad(options) {
			if(options.type!=null){
				this.reqdata.payType=options.type
				uni.setNavigationBarTitle({
					title:this.navList[options.type].state
				})
			}
			if(options.status!=null){
				this.reqdata.status=options.status
			}
			this.loadData('refresh');
		},
		methods: {
			async payOrder(data){
				uni.showLoading({
					title: "创建订单中"
				})
				let code=await uni.login({
					provider: 'weixin'
				})
				code = code[1].code
				let res=await this.$yunapi('user-center', 'loginByWeixin', {code})
				console.log(res)
				uni.setStorageSync('uniIdToken', res.token)
				uni.setStorageSync('uni_id_token_expired', res.tokenExpired)
				if(!this.userInfo.openid){
					let openid=res.userInfo.wx_openid["mp-weixin"]
					let res2=await update_openid({openid})
				}
				await this.$store.dispatch('user/GetInfo')
				uniCloud.callFunction({
				  name: 'pay',
				  data: {
				    provider:"wxpay",
				    outTradeNo: data.id,
					userOrder:data
				  }
				}).then(res=>{
					console.log(res);
					if (res.result.orderInfo) {
					  return new Promise((resolve, reject) => {
					    uni.requestPayment({
					      ...res.result.orderInfo,
					      complete() {
							  uni.hideLoading()
							resolve(res.result.outTradeNo)
					      }
					    })
					  })
					} else {
						uni.hideLoading()
					  throw new Error(res.result.msg)
					}
				}).then(outTradeNo=>{
					this.checkPay(outTradeNo)
				})
			},
			//顶部tab点击
			tabClick(index,payType) {
				this.reqdata.payType = payType
				uni.setNavigationBarTitle({
					title:this.navList[index].state
				})
				this.loadData('refresh');
			},
			toGoods(goods){
				if(this.reqdata.payType==1){
					uni.navigateTo({
						url:"../../goods/goods-integral?id="+goods.productId
					})
				}else{
					uni.navigateTo({
						url:"../../goods/goods?id="+goods.productId
					})
				}
			},
			checkPay(outTradeNo){
				get_order_by_id({id:outTradeNo}).then(res=>{
					if(res.data.status==-2){
						uni.showModal({
							title:"提示"	,
							content:"未支付成功",
							confirmText:"刷新",
							success: (re) => {
								if(re.confirm){
									this.checkPay(outTradeNo)
								}
							}
						})
					}else{
						uni.showModal({
							title:"提示"	,
							content:"支付成功",
							success: (re) => {
								uni.redirectTo({
									url:"../../../pages/user/order/order-intergral?status=-1"
								})
							}
						})
					}
				})
			},
			confirmOrder({id}){
				redeem_confirm({id}).then(res=>{
					uni.showToast({
						icon:"success",
						title:"收货成功！"
					})
					this.loadData('refresh');
				})
			},
			// 加载商品，下拉刷新|上拉加载
			async loadData(type = 'add', loading) {

				if (this.loadmoreType === 'loading') {
					// 防止重复加载
					return;
				}

				if (loading == 1 || type == 'refresh') {
					// 从首页开始加载
					this.reqdata.current = 1;
				}

				// 没有更多直接返回
				if (type === 'add') {
					if (this.loadmoreType === 'nomore') {
						return;
					}
					// 加载中
					this.loadmoreType = 'loading';
				} else {
					// 更多
					this.loadmoreType = 'more'
				}
				goods_redeem_order(this.reqdata).then(res => {
					console.log(res)
					if (res.code === 200) {
						if (res.data.records && res.data.records.length > 0) {
							if (loading == 1 || type == 'refresh') {
								this.datas = [];
							}
							this.$set(this,"datas",[...this.datas, ...res.data.records])

							if (res.data.records.length >= this.reqdata.size) {
								this.reqdata.current++;
								this.loadmoreType = 'more'
							} else {
								this.loadmoreType = 'nomore'
							}
						} else {
							if (loading == 1 || type == 'refresh') {
								this.datas = [];
							}
							this.loadmoreType = 'nomore'
						}
					}

					if (this.datas.length === 0) {
						this.empty = true;
					}else{
						this.empty = false;
					}

					if (loading == 1) {
						uni.hideLoading()
					} else if (type == 'refresh') {
						uni.stopPullDownRefresh();
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}
	/* 订单状态区 */
	.navbar-area {
		white-space: nowrap;
	}

	.state-area {
		height: 7vh;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
	}

	.nav-item {
		flex: 1;

		&.active {
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				transform: translate(-50%);
				bottom: 0;
				width: 44px;
				height: 0;
				border-bottom: 2px solid $base-color;
			}
		}
	}

</style>
